<template>
  <div class="app-container">
    <!-- Header 头部区域 -->
    <Header></Header>
    <!-- 循环渲染每一个商品的信息 -->
    <div v-for="item in list">
      <Goods
        :name="item.goods_name"
        :img="item.goods_img"
        :price="item.goods_price"
        :state="item.goods_state"
        :id="item.id"
        @state-chengn="newstate"
        :count="item.goods_count"
      ></Goods>
    </div>

    <!-- Footer 区域 -->
    <Footer :full="fullSata" @full-cheng="getFull" :jg="aml" :js="tatal"></Footer>
  </div>
</template>

<script>
// 导入 axios 请求库
import axios from "axios";
// 导入需要的组件
import Header from "@/components/Header/Header.vue";
import Goods from "@/components/Goods/Goods.vue";
import Footer from "@/components/Footer/Footer.vue";

import bus from "@/components/eventBus.js";

export default {
  data() {
    return {
      // 用来存储购物车的列表数据，默认为空数组
      list: [],
      name: "",
      img: "",
      price: "",
      state: "",
      id: "",
      count: "",
    };
  },
  created() {
    this.initList();
    bus.$on("fnadd", val => {
      this.list.some(t => {
        if (t.id === val.id) {
          t.goods_count = val.value;
          return true
        }
      });
    });
  },
  methods: {
    async initList() {
      const { data: res } = await axios.get("https://www.escook.cn/api/cart");
      if (res.status === 200) {
        this.list = res.list;
      }
    },
    newstate(e) {
      this.list.some((t) => {
        if (t.id == e.id) {
          t.goods_state = e.value;
          return true;
        }
      });
    },
    getFull(e) {
      this.list.forEach((t) => (t.goods_state = e));
    },
  },
  computed: {
    // 动态绑定获取是否全选
    fullSata() {
      return this.list.every((t) => t.goods_state);
    },
    // 计算价格
    aml() {
      return this.list
        .filter((t) => t.goods_state)
        .reduce((a, t) => {
          // 价格乘以数量
          return (a += t.goods_price * t.goods_count);
        }, 0);
    },
    // 结算
    tatal(){
      return this.list.filter(t => t.goods_state)
      .reduce((a,t)=>{
        return (a += t.goods_count)
      },0)
    }
  },
  components: {
    Header,
    Goods,
    Footer,
  },
};
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
